﻿using Jhw.Common.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Jhw.Common.Helper
{
    public static class HttpHelper
    {
        public async static Task<string> PostAsync(string url, object postData, Dictionary<string, string> headers = null)
        {
            var handler = new HttpClientHandler() { AutomaticDecompression = System.Net.DecompressionMethods.GZip };
            handler.ServerCertificateCustomValidationCallback = (reqMsg, x509Cert, x509Chain, sslPolicyError) => true;
            using (var httpClient = new HttpClient(handler)) {
                var requestJson = JsonConvert.SerializeObject(postData);

                var httpContent = new StringContent(requestJson, Encoding.UTF8);
                httpContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                if (headers != null) {
                    foreach (var pair in headers) {
                        httpContent.Headers.Add(pair.Key, pair.Value);
                    }
                }
                var rsp = await httpClient.PostAsync(url, httpContent);
                if (rsp.StatusCode != System.Net.HttpStatusCode.OK) {
                    throw new BizException("请求失败", $"POST请求{url}失败，状态码{rsp.StatusCode}， 返回结果为{await rsp.Content.ReadAsStringAsync()}");
                }
                var rspJson = await rsp.Content.ReadAsStringAsync();
                return rspJson;
            }
        }
    }
}
